/** @format */

import { resultsModel } from '../../../sdk'
import { CODE_TYPES } from '../../../errorCode'
import { getTotalCompleteTask, getTodayCompleteGrowTask } from '../task'
import { TASK_RATE_TYPE } from '../../../constants'

export default async function checkTaskLimit(
  context: IContext<{ activityId: string; key: ITaskType; itemId?: string }>,
  { userInfo, activityInfo, task }: IControllerInfos
) {
  const { key: taskType, itemId } = context.data
  const { itemIds } = activityInfo?.tasks?.[taskType] || {}
  if (!taskType) {
    console.error('使用checkTaskLimit， 云函数必须传入taskType参数')
    return
  }
  if (!activityInfo?.tasks?.[taskType]) {
    return resultsModel.error(CODE_TYPES.SYSTEM_ERROR, `该活动缺少${taskType}配置项`)
  }

  if (itemId && !itemIds) {
    return resultsModel.error(CODE_TYPES.SYSTEM_ERROR, `该任务缺少商品配置项`)
  }

  // B端配置商品ids不匹配正确
  if (itemId && itemIds) {
    const itemIdArray: number[] = Array.isArray(itemIds) ? itemIds : itemIds.split(',').map(v => +v)
    if (!itemIdArray.includes(+itemId)) return resultsModel.error(CODE_TYPES.PARAMS_ERROR, '商品id不匹配')
  }

  const { rateType, times = 1 } = activityInfo?.tasks?.[taskType]

  // 永久任务已经完成
  const { completeTimes } = getTotalCompleteTask(taskType, userInfo)
  const hasComplete = completeTimes >= times && rateType === TASK_RATE_TYPE.FOREVER
  if (hasComplete) return resultsModel.error(CODE_TYPES.ERROR_TASK_LIMIT, `该任务已完成，去看看其它任务吧~`)

  // 每日任务今天已经完成
  const { todayCompleteTimes, todayTaskInfo } = getTodayCompleteGrowTask(taskType, task)
  const hasCompleteToday = times && todayCompleteTimes === times && rateType === TASK_RATE_TYPE.EVERYDAY
  if (hasCompleteToday) {
    return resultsModel.error(CODE_TYPES.ERROR_TASK_LIMIT, `该任务今天已完成，明天再来吧~`)
  }

  // 今日任务该商品已经完成
  const itemHasCompleteToday =
    todayTaskInfo.find(v => v.itemId && v.itemId === itemId) && rateType === TASK_RATE_TYPE.EVERYDAY

  if (itemHasCompleteToday) {
    return resultsModel.error(CODE_TYPES.PARAMS_ERROR, '今日该商品任务已完成')
  }
}
